package com.odianyun.hello.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.odianyun.hello.mapper.UUserIdentityMapper;
import com.odianyun.hello.model.DTO.IUUserIdentityDTO;
import com.odianyun.hello.service.IUUserIdentityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UUserIdentityServiceImpl implements IUUserIdentityService {

    @Resource
    private UUserIdentityMapper userIdentityMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;
    public static final String CACHE_USER_IDENTITY_KEY_PREFIX="useridentity";

    @Override
    public void updateIdentity(IUUserIdentityDTO dto) {
        dto.setExtFiled1(JSONObject.toJSONString(dto.getExtFiled1List()));
        dto.setExtFiled1List(JSONObject.parseArray(dto.getExtFiled1()));
        int row = userIdentityMapper.updateIdentity(dto);
        System.out.println(dto.getExtFiled1()+dto.getId());
        //System.out.println(row);
        if(row > 0){
            String key = CACHE_USER_IDENTITY_KEY_PREFIX + dto.getId();
            ListOperations<String,String> listOperations = redisTemplate.opsForList();
            redisTemplate.delete(key);
            listOperations.leftPushAll(key, dto.getExtFiled1List());
            redisTemplate.expire(key, 5, TimeUnit.MINUTES);
        }
    }

    @Override
    public List<String> findLabelById(Long id) {
        String key = CACHE_USER_IDENTITY_KEY_PREFIX + id;
        ListOperations listOperations = redisTemplate.opsForList();
        List<String> list = listOperations.range(key,0,-1);
        if(!CollectionUtils.isEmpty(list)){
            System.out.println("使用了缓存");
            return list;
        }
        String userLable =userIdentityMapper.findLabelById(id);
        if(StringUtils.isNotBlank(userLable)){
            list = JSONObject.parseArray(userLable,String.class);
            listOperations.leftPushAll(key,list);

        }
        return list;
    }
}
